﻿using System;
using System.Linq;
using SingleTable.Model;
using Xtensive.Orm;
using Xtensive.Orm.Configuration;
using Xtensive.Orm.Providers;

namespace SingleTable
{
    public class Program
    {
        /* During execution of this code sample, DataObjects.Net creates 1 table:
            * 'Beverage' with columns 'Id', 'TypeId', 'Name', 'IsCarbohydrated', 'Sweetener', 'AlcoholContent'
            * More on 'SingleTable': http://martinfowler.com/eaaCatalog/singleTableInheritance.html
        */

        public static void Main()
        {
            // Loading domain configuration section with name "Default".
            var domainConfiguration = DomainConfiguration.Load("Default");
            var domain = Domain.Build(domainConfiguration);

            using (var session = domain.OpenSession()) {
                // Subscribing to Session event to display actual DbCommands
                session.Events.DbCommandExecuted += (sender, args) => Console.WriteLine(args.Command.ToHumanReadableString());

                using (var tx = session.OpenTransaction()) {

                    Console.WriteLine("\n* Creating soft drink leads to 1 insert: to 'Beverage' table");
                    var cola = new SoftDrink(session) {
                        Name = "Coca Cola",
                        IsCarbohydrated = true,
                        Sweetener = "sugar"
                    };
                    tx.Complete();
                }

                using (var tx = session.OpenTransaction()) {
                    Console.WriteLine("\n* Querying soft drinks is translated to 'select from Beverage filter by TypeId' query");
                    var softDrinks = session.Query.All<SoftDrink>().ToList();

                    Console.WriteLine("\n* Querying just beverages is translated to 'select from Beverage' query");
                    var beverages = session.Query.All<Beverage>().ToList();
                    tx.Complete();
                }
            }
        }
    }
}